<template>
  <div class="container">
    <navigate @answerBack="back" @rightClick="answerCardShow = !answerCardShow">
      测评答题
      <template v-slot:right>答题卡</template>
    </navigate>
    <!-- 答题卡 -->
    <div class="answerCard flex_column" v-if="answerCardShow">
      <div class="header flex_row flex_align_center between">
        <div class="title">答题情况：</div>
        <div class="flex_row flex_align_center">
          <div class="status flex_row flex_align_center yes">
            <div class="circle"></div>
            已作答
          </div>
          <div class="status flex_row flex_align_center no">
            <div class="circle"></div>
            未作答
          </div>
        </div>
      </div>
      <div class="main flex_row">
        <div
          :class="[
            'item',
            { over: item.user_answer_id },
            { current: currentQuestion == index + 1 },
          ]"
          v-for="(item, index) in answerList"
          @click="currentQuestion = index + 1"
          :key="index"
        >
          {{ index + 1 }}
        </div>
      </div>
      <div class="mask" @click="answerCardShow = false"></div>
    </div>

    <!-- 题目 -->
    <div class="question">
      <div class="title">{{ title }}</div>
      <!-- 进度 -->
      <div class="schedule">第{{ currentQuestion }}题/共{{ total }}题</div>
      <div class="line"></div>
      <!-- 问题 -->
      <div class="question" v-if="answerList[currentQuestion - 1]">
        {{ currentQuestion + "." + answerList[currentQuestion - 1].name }}
      </div>
      <div class="answer flex_column">
        <template v-if="answerList[currentQuestion - 1]">
          <div
            @click="selectQuestion(item)"
            :class="[
              'item',
              {
                current:
                  answerList[currentQuestion - 1].user_answer_id == item.id,
              },
            ]"
            v-for="(item, index) in answerList[currentQuestion - 1].answers"
            :key="index"
          >
            {{ item.name }}
          </div>
        </template>
      </div>
    </div>
    <button class="btn" @click="next(accomplish(answerList))">
      {{ accomplish(answerList) ? "提交答案" : "下一题" }}
    </button>
    <button class="prev" @click="prev">上一题</button>
  </div>
</template>

<script>
import {
  apiGetQuestion,
  apiTeamSubmitQuestion,
  apiTempSubmitQuestion,
  apiGetPrevRecord,
} from "@/api/task.js";
export default {
  data() {
    return {
      // 显示答题卡
      answerCardShow: false,
      // 答案列表
      answerList: [],
      // 量表名
      title: "",
      // 当前题目数
      currentQuestion: 1,
      // 总题数
      total: 0,
      // 开始时间
      startTime: 0,
      // 防止点击过快的锁
      lock: true,
      // 答题间隔的锁
      lock1: true,
      // 计时
      currentTime: 0,
      timer: null,
      // 测评时间
      minute: 0,
      // 创建人id
      create_user_id: "",
      //任务名称
      task_name: "",
      // 关联id
      relevance_id: "",
      // 预警后要测的量表id
      factor_id: "",
      // 答题间隔
      readTime: 0,
      // 最后一题是否答了两次
      overFlagNum: 0,
    };
  },
  methods: {
    // 获取上次的答题
    async getPrevAnswer() {
      const { trid } = this.$route.params;
      const { data } = await apiGetPrevRecord({ id: trid });
      if (data.code == 200) {
        let tempArr = JSON.parse(data.data.score_result).list;

        this.startTime =
          new Date().getTime() - Number(data.data.finish_used_time) * 1000;
        tempArr.forEach((item, index) => {
          if (item.question_id) {
            this.$set(this.answerList[index], "question_id", item.question_id);
            this.$set(
              this.answerList[index],
              "user_answer_id",
              item.user_answer_id
            );
          }
        });
        this.currentQuestion = tempArr.filter(
          (item) => item.question_id
        ).length;
      }
      this.timekeeping();
    },
    // 上一题
    prev() {
      if (this.currentQuestion == 1)
        return this.$toast.fail("已经是最上面的一题了!");
      this.currentQuestion--;
    },

    // 记录答案
    async recordAnswer() {
      // 时间
      // let time = Math.floor((new Date().getTime() - this.startTime) / 1000);
      // const { tid, sid, rid, trid } = this.$route.params;
      // const answerList = this.getAnswer();
      // const params = {
      //   task_id: tid,
      //   rating_scale_id: sid,
      //   is_parent_test: rid,
      //   type: 1,
      //   id: trid,
      //   answer: answerList,
      //   finish_used_time: time,
      // };
      // const { data } = await apiTempSubmitQuestion(params);
      // if (data.code == 200) {
      //   if (data.data.id != this.$route.params.trid) {
      //     this.$router.push({
      //       params: { ...this.$route.params, trid: data.data.id },
      //     });
      //   }
      setTimeout(() => {
        this.lock = true;
        if (this.currentQuestion == this.answerList.length) {
          if (this.overFlagNum <= 2) this.overFlagNum++;

          let over = this.answerList.every((item) => item.user_answer_id);
          if (!over) return this.$toast.fail("还有题目没有答完!");

          if (this.overFlagNum == 2) {
            return this.$toast.fail("已经是最后一题了!");
          } else {
            return;
          }
        }
        this.currentQuestion++;
      }, 500);
      // }
    },
    // 获取答案
    getAnswer() {
      // 答案列表
      const list = this.answerList.map((item) => {
        return {
          question_id: item.question_id,
          user_answer_id: item.user_answer_id,
        };
      });
      const answerList = JSON.stringify({ list: list });
      return answerList;
    },
    // 下一题
    async next(type) {
      // 有type提交答案
      if (type) {
        this.$popup({
          visible: false,
          title: "提示",
          message: `<div>确定结束测评并提交答案吗？</div>
            <div style="white-space: nowrap;font-size: 16px;color: #959595;">（测评结果在功能中心--任务测评中查看）</div>
          `,
          confirmOperate: async () => {
            // 时间
            let time = Math.floor(
              (new Date().getTime() - this.startTime) / 1000
            );
            const { tid, sid, rid, trid, relevance_id, factor_id } =
              this.$route.params;
            const answerList = this.getAnswer();
            const params = {
              task_id: tid,
              rating_scale_id: sid,
              answer: answerList,
              is_parent_test: rid,
              type: factor_id == 0 ? 2 : 1,
              finish_used_time: time,
              id: 0,
              relevance_id: relevance_id || 0,
              factor_id: factor_id || 0,
              create_time: new Date().valueOf(),
              create_user_id: this.create_user_id,
              task_name: this.task_name,
            };
            const { data } = await apiTeamSubmitQuestion(params);
            if (data.code == 200) {
              if (data.data.relevance_id > 0) {
                this.$router.replace(
                  `/teamAnswer/${data.data.relevance_id}/${tid}/${rid}/0/${data.data.relevance_id}/${data.data.factor_id}`
                );

                this.getQuestion();
                this.currentQuestion = 1;
                return;
              }
              if (data.data.relevance_id == 0 && data.data.task_id > 0) {
                this.$router.replace(
                  `/teamAnswer/${data.data.rating_scale_id}/${data.data.task_id}/${rid}/0/0/0`
                );
                this.getQuestion();
                this.currentQuestion = 1;
                return;
              }
              if (data.data.relevance_id == 0 && data.data.task_id == 0) {
                this.$toast.success("提交成功!");
                setTimeout(() => {
                  this.$router.push("/nav/evaluation");
                }, 2000);
              }
              return;
            }
          },
        });
        return;
      }
      if (!this.answerList[this.currentQuestion - 1].user_answer_id)
        return this.$toast.fail("请选择答案!");

      let over = this.answerList.every((item) => item.user_answer_id);
      if (!over) return this.$toast.fail("还有题目没有答完!");

      if (this.currentQuestion == this.answerList.length)
        return this.$toast.fail("已经是最后一题了!");
      this.currentQuestion++;
    },

    // 选择题目
    selectQuestion(item) {
      if (this.lock && this.lock1) {
        this.lock = false;
        this.lock1 = false;
        setTimeout(() => {
          this.lock1 = true;
        }, this.readTime * 1000);
        this.$set(
          this.answerList[this.currentQuestion - 1],
          "user_answer_id",
          item.id
        );
        this.$set(
          this.answerList[this.currentQuestion - 1],
          "question_id",
          item.question_id
        );
        this.recordAnswer();
      } else {
        this.$toast.fail("您答题的太快了！");
      }
    },
    // 获取题目
    async getQuestion(callback) {
      const { sid, rid, tid } = this.$route.params;
      const params = {
        rating_scale_id: sid,
        task_id: tid,
      };
      const { data } = await apiGetQuestion(params);
      if (data.code == 200) {
        this.answerList = data.data.questions;
        this.title = data.data.name;
        this.total = data.data.questions.length;
        this.startTime = new Date().getTime();
        this.create_user_id = data.data.publish_user_id;
        this.task_name = data.data.task_name;
        this.minute = Number(data.data.subject_time.split(".")[0]);
        // 答题间隔
        this.readTime = Number(data.data.read_time);

        callback && callback();
      }
    },
    back() {
      this.$popup({
        visible: false,
        title: "提示",
        message: "退出将不会保存记录，是否退出?",
        confirmOperate: () => {
          this.$router.push("/nav/evaluation");
        },
      });
    },
    // 计时
    timekeeping() {
      if (this.minute == "0.00") return;
      let taskTime;
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        this.currentTime = new Date().valueOf();
        taskTime = this.currentTime - this.startTime;

        if (taskTime / 1000 > this.minute) {
          clearInterval(this.timer);
          this.$toast.success("您的答题时间已用完！即将返回！");
          setTimeout(() => {
            this.$router.push("/nav/evaluation");
          }, 2000);
        }
      }, 1000);
    },
  },
  computed: {
    // 判断题目是否做完
    accomplish() {
      return (answerList) => {
        return answerList.every((item) => item.user_answer_id);
      };
    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  created() {
    this.getQuestion();
  },
};
</script>

<style lang="less" scoped>
@import "./css/index.less";
</style>